package com.doc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.doc.model.ApiDoc;
import com.doc.model.ApiVersion;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.wjw.utils.GUID;
import com.wjw.utils.HttpUtil;
import com.wjw.utils.ListUtil;
import com.wjw.utils.RegExpUtil;
import com.wjwframework.jfinal.controller.BaseController;
import com.wjwframework.jfinal.verify.CommonVerify;
import com.wjwframework.jfinal.vo.PageNavation;
import com.wjwframework.jfinal.vo.Response;
import com.wjwframework.jfinal.web.shiro.ShiroUtils;

public class DocController extends BaseController<ApiDoc>{
	
	private ApiDoc docDao=ApiDoc.dao;
	
	private ApiVersion verDao=ApiVersion.dao;
	
	/**
	 * 查询文档集合JSON
	 */
	public void getData(){
		Response resp=new Response();
		PageNavation<ApiDoc> page=getPageNavation(getRequest());
		if(getPara("sort")==null){
			page.setSort("create_date");//默认排序字段
		}
		page=docDao.findList(page);//获取集合对象
		resp.result.put("totalRow", page.getTotalRow());//总记录数
		resp.result.put("totalPage", page.getTotalPage());//总记录数
		List<ApiDoc> list=(List<ApiDoc>) page.getParamMap().get("list");
		String ids="";
		for(ApiDoc item:list){
			ids+=",'"+item.getId()+"'";
		}
		List<ApiVersion> verList=null;
		if(list.size()>0){
			verList=verDao.getVersionsByIds(ids.substring(1));
		}else{
			verList=new ArrayList<ApiVersion>();
		}
		// key docId value apiVersion
		Map<String, List<ApiVersion>> verMap=new HashMap<String,List<ApiVersion>>();
		for(ApiVersion verItem:verList){
			List<ApiVersion> item=null;
			if(!verMap.containsKey(verItem.getDocId())){
				item=new ArrayList<ApiVersion>();
				item.add(verItem);
			}else{
				item=verMap.get(verItem.getDocId());
				item.add(verItem);
			}
			verMap.put(verItem.getDocId(), item);
		}
		//最终返回json对象
		List<Record> reList=new ArrayList<Record>();
		for(ApiDoc item:list){
			Record re=item.toRecord();
			re.set("verList", verMap.get(item.getId()));
			reList.add(re);
		}
		resp.result.put("list",reList);//数据集
		resp.result.put("pageNumList", page.getPageNumList());//分页页码列表
		renderJson(resp);
	}
    
	/**
     * 保存/文档和版本
     */
	@Before(value={Tx.class,CommonVerify.class})
    public void save(){
    	Response response=new Response();
		//seq存在则判断是否合法
		String seq = getPara("doc.seq");
		if(StringUtils.isNotBlank(seq) && !RegExpUtil.isNumeric(seq)){
    		response.setErrcode(1);
    		response.setMsg("排序值不是整型!");
    		renderJson(response);
    		return;
    	}
    	ApiDoc doc=getModel(ApiDoc.class,"doc");//文档对象
    	doc.setId(GUID.create());
    	ApiVersion docVer=getModel(ApiVersion.class,"docVer");//文档对象
    	docVer.setId(GUID.create());
    	docVer.setDocId(doc.getId());
    	docVer.setContentCode(getPara("doc-editormd-markdown-doc"));//编辑器代码
    	docVer.setContentHtml(getPara("contentHtml"));//html代码
    	//空值判断
    	if(StringUtils.isBlank(doc.getName()) || StringUtils.isBlank(doc.getProjectId())){
    		response.setErrcode(1);
    		response.setMsg("名称/所属项目");
    		renderJson(response);
    		return;
    	}
    	Map<String, Object> paramMap=new HashMap<String, Object>();
    	//检测名称唯一性
		paramMap.put("name",doc.getName());
		if(docDao.isExistName(paramMap)){
			response.setErrcode(7);
    		response.setMsg("名称已存在!");
    		renderJson(response);
    		return;
		}
    	//如果序号为空获取下一个序号
    	if(doc.getSeq()==null){
    		doc.setSeq(docDao.getNextSeq());
    	}
		Boolean b=doc.save();
		Boolean b2=docVer.save();
		
        if(!b || !b2){
        	response.setErrcode(3);
        	response.setMsg("保存失败");
        }
       renderJson(response);
	}
    
	/**
     * 保存/添加新版本
     */
	@Before(value={Tx.class,CommonVerify.class})
    public void saveVer(){
    	Response response=new Response();
    	ApiVersion docVer=getModel(ApiVersion.class,"docVer");//文档对象
    	ApiDoc doc = docDao.findById(docVer.getDocId());
    	docVer.setContentCode(getPara("doc-editormd-markdown-doc"));//编辑器代码
    	docVer.setContentHtml(getPara("contentHtml"));//html代码
    	//空值判断
    	if(StringUtils.isBlank(docVer.getDocId()) || StringUtils.isBlank(docVer.getVersion())){
    		response.setErrcode(1);
    		response.setMsg("所属文档/版本号");
    		renderJson(response);
    		return;
    	}
    	
    	docVer.setId(GUID.create());
    	Boolean b=docVer.save();
        if(!b){
        	response.setErrcode(3);
        	response.setMsg("保存失败");
        }
       renderJson(response);
	}
	
	/**
     * 修改/文档和版本
     */
	@Before(value={Tx.class,CommonVerify.class})
    public void editor() {
		Response response=new Response();
		if(ShiroUtils.getRoleCoding().equals("demo") ){
    		response.setErrcode(-1);
    		response.setMsg("演示demo,无权限操作!");
    		renderJson(response);
    		return;
    	}
    	ApiDoc doc=getModel(ApiDoc.class,"doc");
    	ApiVersion docVer=getModel(ApiVersion.class,"docVer");
    	docVer.setDocId(doc.getId());
    	if(getPara("doc-editormd-markdown-doc")!=null){
    		docVer.setContentCode(getPara("doc-editormd-markdown-doc"));//编辑器代码
    	}
    	if(getPara("contentHtml")!=null){
    		docVer.setContentHtml(getPara("contentHtml"));//html代码
    	}
    	//空值判断
    	if(StringUtils.isBlank(doc.getId())){
    		response.setErrcode(1);
    		response.setMsg("所属文档");
    		renderJson(response);
    		return;
    	}
    	
    	if(doc.getName()!=null){
    		Map<String, Object> paramMap=new HashMap<String, Object>();
    		paramMap.put("id", doc.getId());
    		//检测名称唯一性
    		paramMap.put("name",doc.getName());
    		if(docDao.isExistName(paramMap)){
    			response.setErrcode(7);
    			response.setMsg("文档名称已存在!");
    			renderJson(response);
    			return;
    		}
    	}
    	doc.setUpdateDate(new Date());
    	docVer.setUpdateDate(new Date());
    	//如果序号为空则不修改
    	if(doc.getSeq()==null){
    		doc.remove("seq");
    	}
    	Boolean b=doc.update();
    	Boolean b2=docVer.update();
        if(!b || !b2){
        	response.setErrcode(3);
        	response.setMsg("修改失败");
        }
        renderJson(response);
    }
   
	/**
     * 根据id获取文档及版本
     */
    public void findById(){
    	Response response=new Response();
    	String id=getPara("id");//文档id
    	String verId=getPara("verId");//版本id
    	if(id==null){
    		response.setErrcode(1);
    		response.setMsg("id主键不能为空!");
    		return;
    	}
		response.result.put("doc",docDao.findById(id));//查询文档
		if(verId==null){
			response.result.put("docVer",verDao.getNewVersion(id));//查询文档最新版本
		}else{
			response.result.put("docVer",verDao.findById(verId));//查询文档对应版本
		}
		response.result.put("verlist",verDao.getVersionsById(id));//根据id获取版本集合按创建时间升序
    	renderJson(response);
    }
    
	/**
     * 根据版本id获取版本
     */
    public void findByVerId(){
    	Response response=new Response();
    	String id=getPara("id");//版本id
    	if(id==null){
    		response.setErrcode(1);
    		response.setMsg("id主键不能为空!");
    		return;
    	}
		response.result.put("docVer",verDao.findById(id));//查询文档
    	renderJson(response);
    }
    
    /**
     * 根据文档id获取版本集合
     */
    public void findByDocId(){
    	Response response=new Response();
    	String id=getPara("id");//文档id
    	if(id==null){
    		response.setErrcode(1);
    		response.setMsg("id不能为空!");
    		return;
    	}
		response.result.put("docVerList",verDao.find("SELECT * FROM api_version WHERE doc_id=? ORDER BY create_date asc", id));//查询文档
    	renderJson(response);
    }
    
	/**
	 * 查看当前文档html
	 */
	public void viewHtml(){
		setAttr("req", getRequest());
		String id=getPara("id");
		ApiVersion bean = verDao.findById(id);//查询文档
		setAttr("bean", bean);
		renderFreeMarker("/template/apidoc/doc/view.html");
	}
    
    /**
     * 删除文档
     */
    @Before(value={Tx.class})
    public void del(){
		Response response = new Response();
		if(ShiroUtils.getRoleCoding().equals("demo") ){
    		response.setErrcode(-1);
    		response.setMsg("演示demo,无权限操作!");
    		renderJson(response);
    		return;
    	}
		String ids = ListUtil.getStrSqlByStrs(getPara("ids"));

		Boolean b = docDao.deleteByIds(ids);// 删除文档
		Boolean b2 = verDao.deleteByDocIds(ids);// 删除版本
		if (!b || !b2) {
			response.setErrcode(3);
			response.setMsg("删除失败");
		}
		renderJson(response);
    }

    /**
     * 获取所有版本并分组
     */
    public void getAllVersion(){
    	Response response=new Response();
    	List<ApiVersion> verList=verDao.find("SELECT * FROM api_version order by create_date asc");//查询所有版本
		// key docId value apiVersion
		Map<String, List<ApiVersion>> verMap=new HashMap<String,List<ApiVersion>>();
		for(ApiVersion verItem:verList){
			List<ApiVersion> item=null;
			if(!verMap.containsKey(verItem.getDocId())){
				item=new ArrayList<ApiVersion>();
				item.add(verItem);
			}else{
				item=verMap.get(verItem.getDocId());
				item.add(verItem);
			}
			verMap.put(verItem.getDocId(), item);
		}
		response.result.put("verMap",verMap);//文档版本分组集合
    	renderJson(response);
    }
    
    /**
     * 查询所有启用的接口文档
     */
    public void getAlldoc(){	
    	Response response=new Response();
    	String pro_id=getPara("pro_id");//项目id
    	List<Record> list=docDao.findAllList(pro_id);//查询所有项目对象
		response.result.put("list",list);
    	renderJson(response);
    }
    
    /**
     * 接口调试工具页
     */
    public void debug(){
    	setAttr("req", getRequest());
    	renderFreeMarker("front/tools/debug.html");
    }
    
	/**
     * http请求,由服务器进行跨域请求。浏览器会限制跨域
     */
    public void http(){
    	Response response=new Response();
    	String resp=null;
    	String url=getPara("url");//url
    	String method=getPara("method");//请求方法
    	Map<String, String> params =null;
    	Map<String, String> header =null;
    	if(getPara("p")==null){
    		params = getParamMap("params");//参数对象
    		
    	}
    	if(getPara("h")==null){
    		header = getParamMapHeader("header");//头属性对象
    	}
    	
    	if(method.equalsIgnoreCase("POST")){
    		resp = HttpUtil.post(url, params, header);
    	}else if(method.equalsIgnoreCase("GET")){
    		resp = HttpUtil.get(url, params, header);
    	}
    	response.result.put("response", resp);
    	renderJson(response);
    }
    
	/**
	 * 获取request中带有前缀的参数到Map
	 */
	public Map<String, String> getParamMap(String prefix) {
		Map<String, String> paramMap = new HashMap<String, String>();
		Enumeration<String> paramNames = getParaNames();
		String paramName = "";
		String paramValue = "";
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement();
			if(paramName.startsWith(prefix)){//指定前缀
				paramValue = getPara(paramName);
				paramMap.put(paramName.substring(paramName.indexOf(".")+1), paramValue);
			}
		}
		return paramMap;
	}
	
	/**
	 * 获取request中带有前缀的参数到Map(header)
	 */
	public Map<String, String> getParamMapHeader(String prefix) {
		Map<String, String> paramMap = new HashMap<String, String>();
		Enumeration<String> paramNames = getParaNames();
		String paramName = "";
		String paramValue = "";
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement();
			if(paramName.startsWith(prefix)){//指定前缀
				paramValue = getPara(paramName);
				paramMap.put(paramName.substring(paramName.indexOf(".")+1), paramValue.replaceAll("@@@", "="));
			}
		}
		return paramMap;
	}
}
